package com.ym.b2b.order.controller;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ym.b2b.commons.conf.WebProviderTokenUser;
import com.ym.b2b.commons.controller.BaseController;
import com.ym.b2b.commons.util.FileUtil;
import com.ym.b2b.order.sqlbean.EmSOrder;
import com.ym.b2b.order.xc.FtpUtil;
import com.ym.b2b.order.xc.XcService;
import com.ym.b2b.order.xc.sqlbean.DataPackageERP;
import com.ym.b2b.order.xc.sqlbean.XcSaleDetail;
import com.ym.b2b.order.xc.sqlbean.XcStock;
import com.ym.b2b.provider.service.EmBProviderProductService;
import com.ym.b2b.provider.sqlbean.EmBProviderProduct;
import com.zc.commons.base.Page;
import com.zc.commons.base.Result;
import com.zc.export.ExcelUtil;

/**
 * 宣城医药专属功能Controller
* @ClassName: XCB2BController 
* @Date 2017年8月22日 下午3:24:53 
* @CopyRight 珍诚医药在线股份有限公司
 */
@Controller
@RequestMapping("/xcB2B")
public class XCB2BController extends BaseController {
	
    @Autowired
    private XcService              xcService;
    @Autowired
    private EmBProviderProductService              providerProductService;
    
    
    private final static String localSavePath = "D:/b2bDownload/";
    
    /**
     * 根据XSAZ号查询获取所以可以下载的资料列表
     */
    @RequestMapping(value = "getDataPackageERPList.s")
    @ResponseBody
    public Result getDataPackageERPList(EmSOrder emSOrder){
    	Result ret = new Result();
        try {
        	List<DataPackageERP> list = new ArrayList<DataPackageERP>();
			if (emSOrder.getOrderCode().trim() == null || "".equals(emSOrder.getOrderCode().trim())) {
			}else{
				// 通过ErpCode在ERP数据库中查询相关信息
				list = xcService.getDataPackageERPList(emSOrder.getOrderCode());
			}
            Page<EmSOrder> page = new Page<EmSOrder>();
            page.setRows(list);
            ret.setResultPage(page);
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return ret;
    }
    
    /**
     * 根据XSAZ号下载质检单
     */
    @RequestMapping(value = "downErpFile.s")
    @ResponseBody
    public Result downErpFile(DataPackageERP data) {
        Result ret = new Result();
        try {
            // 通过ErpCode在ERP数据库中查询相关信息
            List<DataPackageERP> list = new ArrayList<>();
            list.add(data);
            if(list.size()>0){
            	// 从ERP下载文件到本地目录
            	String localPath = localSavePath + data.getDjbh().trim();
            	FtpUtil.downloadFtpFiles(list, localPath);
            	// 打包文件
            	ret.putData("outPath", localPath + File.separatorChar + data.getSpmch() + data.getImageid() + data.getExtend());
            	ret.putData("title", data.getSpmch() + data.getExtend());
            }else{
            	ret.setCode("101");
            	ret.setResult("暂时没有资料可以下载");
            }
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return ret;
    }
    
    /**
     * 根据XSAZ号批量打包下载质检单
     */
    @RequestMapping(value = "uploadOrderQuality.s")
    @ResponseBody
    public Result uploadOrderQuality(EmSOrder emSOrder) {
        Result ret = new Result();
        try {
            // 通过ErpCode在ERP数据库中查询相关信息
            List<DataPackageERP> list = xcService.getDataPackageERPList(emSOrder.getOrderCode());

            if(list.size()>0){
            	// 从ERP下载文件到本地目录
            	String localPath = localSavePath + emSOrder.getOrderCode();
            	FtpUtil.downloadFtpFiles(list, localPath);
            	
            	// 打包文件
            	FileUtil.fileToZip(localPath,localSavePath, emSOrder.getOrderCode());
            	ret.putData("outPath", localSavePath + File.separatorChar + emSOrder.getOrderCode() + ".zip");
            	ret.putData("title", emSOrder.getOrderCode() + ".zip");
            }else{
            	ret.setCode("101");
            	ret.setResult("暂时没有资料可以下载");
            }
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return ret;
    }
    
   
    /**
     * 查询供应商销售流向
     * @Title: searchPageSalesDetail 
     */
    @RequestMapping(value = "searchXcPageSalesDetail.s")
    @ResponseBody
    public Result searchXcPageSalesDetail(XcSaleDetail saleDetail,Page<XcSaleDetail> page, HttpServletRequest req){
    	Result result = new Result();
    	WebProviderTokenUser provider = getWebProviderTokenUser(req);
    	if (provider == null) {
    		result.setCode("101");
    		result.setResult("未登录");
    		return result;
    	}
		List<XcSaleDetail> list = this.searchXcSalesDetail(saleDetail, page, provider);
		if (page.getPage() * page.getPageSize() > list.size()) {
			page.setRows(list.subList((page.getPage() - 1) * page.getPageSize(), list.size()));
		}else{
			page.setRows(list.subList((page.getPage() - 1) * page.getPageSize(), page.getPage() * page.getPageSize()));

		}
		page.setTotalRow(Long.valueOf(list.size()));
		
        result.setResultPage(page);
        req.setAttribute("result", result);
    	return result;
    }
    
    /**
     * 查询供应商销售流向, 导出excel
    * @Title: searchXcPageSalesDetailExcel 
     */
    @RequestMapping(value = "searchXcPageSalesDetailExcel.s")
    @ResponseBody
    public Result searchXcPageSalesDetailExcel(XcSaleDetail saleDetail,Page<XcSaleDetail> page, HttpServletRequest req){
    	Result result = new Result();
    	WebProviderTokenUser provider = getWebProviderTokenUser(req);
    	if (provider == null) {
    		result.setCode("101");
    		result.setResult("未登录");
    		return result;
    	}
		List<XcSaleDetail> list = this.searchXcSalesDetail(saleDetail, page, provider);
		page.setTotalRow(Long.valueOf(list.size()));
		page.setRows(list);
		
    	ExcelUtil<XcSaleDetail> excelUtil = new ExcelUtil<XcSaleDetail>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("model", page.getRows());
        result = excelUtil.createExcel("xcSalesDetail", map);
    	return result;
    }
    
    /**
    * @Title: searchXcPageStock 
    * @Author cym
    * @Description: 前台供应商查询库存
    * @param xcStock
    * @param page
    * @param req
     */
    @RequestMapping(value = "searchXcPageStock.s")
    @ResponseBody
    public Result searchXcPageStock(XcStock xcStock,Page<XcStock> page, HttpServletRequest req){
    	Result result = new Result();
    	WebProviderTokenUser provider = getWebProviderTokenUser(req);
    	if (provider == null) {
    		result.setCode("101");
    		result.setResult("未登录");
    		return result;
    	}
		List<XcStock> list = this.searchXcStock(xcStock, page, provider);
		if (page.getPage() * page.getPageSize() > list.size()) {
			page.setRows(list.subList((page.getPage() - 1) * page.getPageSize(), list.size()));
		}else{
			page.setRows(list.subList((page.getPage() - 1) * page.getPageSize(), page.getPage() * page.getPageSize()));

		}
		page.setTotalRow(Long.valueOf(list.size()));
		
        result.setResultPage(page);
        req.setAttribute("result", result);
    	return result;
    }
    
    /**
     * 查询供应商销售流向, 导出excel
    * @Title: searchXcPageStockExcel 
     */
    @RequestMapping(value = "searchXcPageStockExcel.s")
    @ResponseBody
    public Result searchXcPageStockExcel(XcStock xcStock,Page<XcStock> page, HttpServletRequest req){
    	Result result = new Result();
    	WebProviderTokenUser provider = getWebProviderTokenUser(req);
    	if (provider == null) {
    		result.setCode("101");
    		result.setResult("未登录");
    		return result;
    	}
		List<XcStock> list = this.searchXcStock(xcStock, page, provider);
		page.setTotalRow(Long.valueOf(list.size()));
		page.setRows(list);
		
    	ExcelUtil<XcStock> excelUtil = new ExcelUtil<XcStock>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("model", page.getRows());
        result = excelUtil.createExcel("xcStock", map);
    	return result;
    }
    
    // 重复用到的方法,查销售/采购流向
    private List<XcSaleDetail> searchXcSalesDetail(XcSaleDetail saleDetail,Page<XcSaleDetail> page, WebProviderTokenUser provider){
    	try{

    		if(saleDetail.getStartRq() != null && !"".equals(saleDetail.getStartRq())){
    			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    			Date dt1 = df.parse(provider.getSearchStartDate());
    			Date dt2 = df.parse(saleDetail.getStartRq());
    			if (dt1.getTime() > dt2.getTime()) {
    				saleDetail.setStartRq(provider.getSearchStartDate());
    			}
    		}else{
				saleDetail.setStartRq(provider.getSearchStartDate());
    		}

			// 根据providerCode查询相应的产品列表, 获取查询的产品组合
			List<EmBProviderProduct> providerProductList = providerProductService.getProviderProductList(provider.getProviderCode());
			StringBuffer sb = new StringBuffer("");
			for (EmBProviderProduct product : providerProductList) {
				sb.append("'" + product.getProductCode() + "',");
			}
			sb.deleteCharAt(sb.length() - 1);
			saleDetail.setSpbhs(sb.toString());
			
			// 通过ErpCode在ERP数据库中查询相关信息
			return xcService.searchXcPageSalesDetail(saleDetail,page ,saleDetail.getType());
			
    	}catch (Exception e) {
        	e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    	return null;
    }
    
    // 重复用到的方法,查库存
    private List<XcStock> searchXcStock(XcStock xcStock,Page<XcStock> page, WebProviderTokenUser provider){
    	try{

    		if(xcStock.getStartRq() != null && !"".equals(xcStock.getStartRq())){
    			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    			Date dt1 = df.parse(provider.getSearchStartDate());
    			Date dt2 = df.parse(xcStock.getStartRq());
    			if (dt1.getTime() > dt2.getTime()) {
    				xcStock.setStartRq(provider.getSearchStartDate());
    			}
    		}else{
    			xcStock.setStartRq(provider.getSearchStartDate());
    		}

			// 根据providerCode查询相应的产品列表, 获取查询的产品组合
			List<EmBProviderProduct> providerProductList = providerProductService.getProviderProductList(provider.getProviderCode());
			StringBuffer sb = new StringBuffer("");
			for (EmBProviderProduct product : providerProductList) {
				sb.append("'" + product.getProductCode() + "',");
			}
			sb.deleteCharAt(sb.length() - 1);
			xcStock.setSpbhs(sb.toString());
			
			// 通过ErpCode在ERP数据库中查询相关信息
			return xcService.searchXcPageStock(xcStock,page);
			
    	}catch (Exception e) {
        	e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    	return null;
    }
}
